
package com.wuye.services.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wuye.common.services.impl.BaseManagerImpl;
import com.wuye.common.util.numeric.NumericUtil;
import com.wuye.common.vo.PageInfo;
import com.wuye.common.vo.ParkingSearchVO;
import com.wuye.common.vo.ParkingUpdateInfo;
import com.wuye.common.vo.RetVO;
import com.wuye.common.vo.StatVO;
import com.wuye.constants.BaseConstants;
import com.wuye.dao.ParkingDao;
import com.wuye.dao.ParkingTypeDao;
import com.wuye.dao.VehicleDao;
import com.wuye.dao.VehicleRelDao;
import com.wuye.entity.Parking;
import com.wuye.entity.ParkingType;
import com.wuye.entity.Vehicle;
import com.wuye.entity.VehicleRel;
import com.wuye.mapper.CommonMapper;
import com.wuye.services.ParkingServiceManager;
import com.wuye.services.ParkingTypeServiceManager;
import com.wuye.util.MyBatisSessionFactory;

@Service("parkingServiceManager")
public class ParkingServiceManagerImpl extends BaseManagerImpl implements ParkingServiceManager 
{
	@Autowired
	private ParkingDao parkingDao;
	@Autowired
	private ParkingTypeDao parkingTypeDao;
	@Autowired
	private VehicleDao vehicleDao;
	
	@Autowired
	private VehicleRelDao vehicleRelDao;
	
	@Autowired
	private Parking parking;
	@Autowired
	private VehicleRel vehicleRel;
	@Autowired
	private ParkingType parkingType;
	@Autowired
	private Vehicle vehicle;
	
	@Autowired
	private ParkingTypeServiceManager parkingTypeService;
	
//	public RetVO saveParkingType(Map<String, Object> map) throws Exception {
//		// TODO Auto-generated method stub
//		RetVO retVo = RetVO.newInstance(BaseConstants.RET_TRUE, "");
//		//String type = (String) map.get("type");
//		JSONArray parkingTypes = (JSONArray) map.get("parkingType");
//		if (parkingTypes != null && parkingTypes.size() > 0) {
//			for (int i = 0; i < parkingTypes.size(); i++) {
//				JSONObject srcParkingType = parkingTypes.getJSONObject(i);
//				if (StrUtil.isNullOrEmpty(srcParkingType.get("parkingTypeId"))) {
//					// 新增
//					this.addParkingType(srcParkingType);
//				} else {
//					// 更改
//					this.updateParkingType(srcParkingType);
//				}
//			}
//		}
//
//		return retVo;
//	}
//
//	private void updateParkingType(JSONObject srcParkingType) {
//		// TODO Auto-generated method stub
//		// TODO Auto-generated method stub
//		ParkingType parkingType = (ParkingType) ParkingType.getDefaultDao().getObject(ParkingType.class, srcParkingType.getInt("parkingTypeId"));
//		
//		Community community = (Community) Community.getDao().getObject(Community.class, srcParkingType.getJSONObject("community").getInt("communityId"));
//		EntityCopyUtil.populate(parkingType,srcParkingType,null);
//		parkingType.setCommunityId(community.getId());
//		parkingType.save();
//	}
//
//	private void addParkingType(JSONObject srcParkingType) {
//		// TODO Auto-generated method stub
//		//Community community = (Community) Community.getDao().getObject(Community.class, srcParkingType.getInt("communityId"));
//		ParkingType parkingType = new ParkingType();
//		EntityCopyUtil.populate(parkingType,srcParkingType,null);
//		Community community = (Community) Community.getDao().getObject(Community.class, srcParkingType.getJSONObject("community").getInt("communityId"));
//		parkingType.setCommunityId(community.getId());
//		parkingType.save();
//	}
//
//	public RetVO removeParkingType(Map<String, Object> map) {
//		RetVO retVo = RetVO.newInstance(BaseConstants.RET_TRUE, "");
//		JSONArray parkingTypeIds = (JSONArray) map.get("parkingType");
//		for (Object parkingTypeId : parkingTypeIds) {
//			ParkingType parkingType = (ParkingType) ParkingType.getDefaultDao().getObject(
//					ParkingType.class, NumericUtil.nullToIntegerZero(parkingTypeId));
//			parkingType.remove();
//		}
//		return retVo;
//	}
//
//	
//
//	public RetVO getParkingType(Map<String, Object> map, int currentPage,
//			int perPageNum) {
//		RetVO retVO = RetVO.newInstance(BaseConstants.RET_TRUE, "");
//		PageInfo pg = parkingDao.getParkingType(map, currentPage, perPageNum);
//		List<Object> dataList = pg.getDataList();
//		JSONArray jsArray = new JSONArray();
//		Map<String,Object> out = new HashMap<String,Object>();
//		if (dataList != null && dataList.size() > 0){
//			for (Object obj : dataList){
//				ParkingType parkingType = (ParkingType)obj;
//				Community community = parkingType.getCommunity();
//				JSONObject jsObj = EntityCopyUtil.getJSONObject(parkingType,null);
//				
//				jsObj.put("community", EntityCopyUtil.getJSONObject(community, new String[]{"communityId","communityName"}));
//				
//				jsArray.add(jsObj);
//				
//			}
//			out.put("jsArray", jsArray);
//			
//		}
//		out.put("pageCount", pg.getTotalPageCount());
//		retVO.setObject(out);
//		return retVO;
//	}
//
//	public RetVO saveParking(Map<String, Object> map) throws Exception {
//		// TODO Auto-generated method stub
//		RetVO retVo = RetVO.newInstance(BaseConstants.RET_TRUE, "");
//		//String type = (String) map.get("type");
//		JSONArray parkings = (JSONArray) map.get("parking");
//		if (parkings != null && parkings.size() > 0) {
//			for (int i = 0; i < parkings.size(); i++) {
//				JSONObject srcParking = parkings.getJSONObject(i);
//				if (StrUtil.isNullOrEmpty(srcParking.get("parkingId"))) {
//					// 新增
//					this.addParking(srcParking);
//				} else {
//					// 更改
//					this.updateParking(srcParking);
//				}
//			}
//		}
//
//		return retVo;
//	}

//	private void updateParking(JSONObject srcParking) {
//		Parking parking = (Parking) Parking.getDefaultDao().getObject(Parking.class, srcParking.getInt("parkingId"));
//		EntityCopyUtil.populate(parking,srcParking,null);
//		ParkingType parkingType= (ParkingType)ParkingType.getDefaultDao().getObject(Parking.class, srcParking.getJSONObject("parkingType").getInt("parkingTypeId"));
//		parking.setParkingType(parkingType);
//		
//		Set<VehicleRel> vhs = parking.getVehicleRels();
//		VehicleRel vehicleRel = null;
//		if (vhs != null && vhs.size() > 0){
//			vehicleRel = vhs.toArray(new VehicleRel[0])[0];
//		}
//		JSONObject srcVehicleRel = srcParking.getJSONObject("vehicleRel");
//		if (srcVehicleRel != null && srcVehicleRel.getJSONObject("room") != null
//				&& srcVehicleRel.getJSONObject("room").get("roomId") != null){
//			Room room = (Room)Room.getDefaultDao().getObject(Room.class, NumericUtil.nullToIntegerZero(srcVehicleRel.getJSONObject("room").get("roomId")));
//			if (room != null){
//				vehicleRel.setRoom(room);
//				vehicleRel.setParking(parking);
//				vehicleRel.setParkingType(parkingType);
//				vehicleRel.setPlateNbr(srcVehicleRel.getString("plateNbr"));
//				parking.setStatusCd(BaseConstants.STATUS_VALID);
//				vehicleRel.save();
//			}
//		}else{
//			if (vehicleRel != null){
//				vehicleRel.remove();
//				parking.setStatusCd(BaseConstants.STATUS_NOT_EFF);
//			}
//		}
//		parking.save();
//	}

//	private void addParking(JSONObject srcParking) {
//		// TODO Auto-generated method stub
//		Parking parking = new Parking();
//		Community community = (Community) Community.getDao().getObject(Community.class, srcParking.getJSONObject("community").getInt("communityId"));
//		parking.setCommunityId(community.getId());
//		EntityCopyUtil.populate(parking,srcParking,null);
//		ParkingType parkingType= (ParkingType)ParkingType.getDefaultDao().getObject(Parking.class, srcParking.getJSONObject("parkingType").getInt("parkingTypeId"));
//		parking.setParkingType(parkingType);
//		//默认空闲状态
//		parking.setStatusCd(BaseConstants.STATUS_NOT_EFF);
//		JSONObject srcVehicleRel = srcParking.getJSONObject("vehicleRel");
//		if (srcVehicleRel != null && srcVehicleRel.getJSONObject("room") != null
//				&& srcVehicleRel.getJSONObject("room").get("roomId") != null){
//			Room room = (Room)Room.getDefaultDao().getObject(Room.class, NumericUtil.nullToIntegerZero(srcVehicleRel.getJSONObject("room").get("roomId")));
//			if (room != null){
//				VehicleRel vehicleRel = new VehicleRel();
//				vehicleRel.setRoom(room);
//				vehicleRel.setParking(parking);
//				vehicleRel.setParkingType(parkingType);
//				vehicleRel.setPlateNbr(srcVehicleRel.getString("plateNbr"));
//				vehicleRel.save();
//				parking.setStatusCd(BaseConstants.STATUS_VALID);
//			}
//		}
//		parking.save();
//	}

	public RetVO removeParking(Map<String, Object> map) 
	{
		RetVO retVo = RetVO.newInstance(BaseConstants.RET_TRUE, "");
		
		try
		{
			JSONArray parkingIds = (JSONArray) map.get("parking");
			
			for (Object parkingId : parkingIds)
			{
				Parking parking = (Parking) Parking.getDefaultDao().getObject(Parking.class, NumericUtil.nullToIntegerZero(parkingId));
				
				if (parking != null)
				{
					parking.remove();					
				}
				
			}
		} 
		catch (Exception e) 
		{
			retVo.setResult(BaseConstants.RET_FALSE);
			e.printStackTrace();
		}		
		
		return retVo;
	}
	

	public void addParking(JSONObject jsonObject) throws Exception 
	{
		parking.setCommunityId(Integer.parseInt(jsonObject.getString("communityId")));
		parking.setParkingNbr(jsonObject.getString("parkingNbr"));
		parking.setParkingPosition(jsonObject.getString("parkingPosition"));
		parking.setParkingType(parkingTypeService.getParkingType(Integer.parseInt(jsonObject.getString("parkingTypeId"))));
		
		parking.setCreateDate(new Date());
		parking.setUpdateDate(new Date());
		parking.setStatusDate(new Date());
		
		log.debug("-------------" + parking.getParkingId());
		
		if (jsonObject.has("vehicleId"))
		{
			parking.setStatusCd(BaseConstants.STATUS_USED);
			parkingDao.addParking(parking);
			
			vehicle = vehicleDao.getVehicle(Integer.parseInt(jsonObject.getString("vehicleId")));
			vehicleRel = (VehicleRel)vehicle.getVehicleRels().toArray(new VehicleRel[0])[0];
			
			parkingType = parkingTypeDao.getParkingType(jsonObject.getInt("parkingTypeId"));
			vehicleRel.setParkingType(parkingType);
			vehicleRel.setParking(parking);
			vehicleRel.setUpdateDate(new Date());
			
			vehicleRelDao.updateVehicleRel(vehicleRel);
			
		}
		else
		{
			parking.setStatusCd(BaseConstants.STATUS_UNUSED);
			parkingDao.addParking(parking);
		}
		
				
	}

	public List<Object> getParkingSearchInfo(Map<String, Object> map) 
	{
		List<ParkingSearchVO> searchVOs = null;
		List<Object> rtnList = null;
		PageInfo pageInfo = null;
		StatVO statVO = null;
		
		int curPage = Integer.parseInt(map.get("page").toString());
				
		int offset = (curPage-1) * BaseConstants.PARKING_PAGE_SIZE;
		map.put("offset", offset);
		map.put("limit", BaseConstants.PARKING_PAGE_SIZE);
		
		int totalRecs = 0;
		int totalPageCount = 0;
		
		SqlSession session = null;
		
		try 
		{
			session = MyBatisSessionFactory.getSession();			
			CommonMapper commonMapper = session.getMapper(CommonMapper.class);
			statVO = commonMapper.getParkingSearchStats(map);
			
			if (statVO != null && statVO.getTotal() > 0)
			{
				totalRecs = statVO.getTotal();
				searchVOs = commonMapper.getParkingSearchInfo(map);
				totalPageCount = totalRecs / BaseConstants.PARKING_PAGE_SIZE;						
				totalPageCount = (totalRecs % BaseConstants.PARKING_PAGE_SIZE) > 0 ? (totalPageCount + 1) : totalPageCount;
				
				pageInfo = new PageInfo();
				pageInfo.setCurrentPage(curPage);
				pageInfo.setPerPageCount(BaseConstants.PARKING_PAGE_SIZE);
				pageInfo.setTotalCount(totalRecs);
				pageInfo.setTotalPageCount(totalPageCount);
				pageInfo.setDataList(searchVOs);
				
				rtnList = new ArrayList<Object>();
				rtnList.add(pageInfo);
				rtnList.add(statVO);
				
			}
			
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}
		
		return rtnList;
	}
	
	public ParkingUpdateInfo getParkingUpdateInfo(int parkingId)
	{
		ParkingUpdateInfo parkingUpdateInfo = null;
		
		try 
		{
			this.parking = parkingDao.getParking(parkingId);
			
			if (parking.getVehicleRels().size() > 0)
			{
				parkingUpdateInfo = parkingDao.getParkingUpdateInfo(parkingId);
			}
			else
			{
				parkingUpdateInfo = new ParkingUpdateInfo();
				parkingUpdateInfo.setCompanyId(parking.getCommunity().getCompanyId());
				parkingUpdateInfo.setCommunityId(parking.getCommunityId());
				parkingUpdateInfo.setParkingTypeId(parking.getParkingType().getParkingTypeId());
				parkingUpdateInfo.setParkingNbr(parking.getParkingNbr());
				parkingUpdateInfo.setParkingPosition(parking.getParkingPosition());
				
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return parkingUpdateInfo;
	}

	@SuppressWarnings("unchecked")
	public void updateParking(JSONObject jsonObject) throws Exception 
	{
		parking = parkingDao.getParking(Integer.parseInt(jsonObject.getString("parkingId")));
		
		parking.setCommunityId(Integer.parseInt(jsonObject.getString("communityId")));
		parking.setParkingNbr(jsonObject.getString("parkingNbr"));
		parking.setParkingPosition(jsonObject.getString("parkingPosition"));
		parking.setParkingType(parkingTypeService.getParkingType(Integer.parseInt(jsonObject.getString("parkingTypeId"))));
		parking.setUpdateDate(new Date());
		parking.setStatusDate(new Date());
		
		/*
		 * 1.本次有关联车辆
		 * 1.1 原来也关联
		 * 1.2 原来不关联
		2.本次没有关联车辆
		2.1原来有关联
		2.2 原来不关联
		*/
		
		if (jsonObject.has("vehicleId"))
		{
			parking.setStatusCd(BaseConstants.STATUS_USED);
			parkingDao.updateParking(parking);
			
			//原来有关联 1.去除原来的关联 2.加上新的关联
			if (parking.getVehicleRels().size() > 0)
			{
				//原来的关联
				vehicleRel = (VehicleRel)parking.getVehicleRels().toArray(new VehicleRel[0])[0];
				
				if (vehicleRel.getVehicle().getVehicleId() != Integer.parseInt(jsonObject.getString("vehicleId")))
				{
					vehicleRel.setParking(null);
					vehicleRel.setParkingType(null);
					vehicleRel.setUpdateDate(new Date());
					vehicleRelDao.updateVehicleRel(vehicleRel);
					
					vehicle = vehicleDao.getVehicle(Integer.parseInt(jsonObject.getString("vehicleId")));
					
					vehicleRel = (VehicleRel)vehicle.getVehicleRels().toArray(new VehicleRel[0])[0];
					
					parkingType = parkingTypeDao.getParkingType(jsonObject.getInt("parkingTypeId"));
					vehicleRel.setParkingType(parkingType);					
					vehicleRel.setParking(parking);					
					vehicleRel.setUpdateDate(new Date());
					
					vehicleRelDao.updateVehicleRel(vehicleRel);
				}
				
			}
			else
			{
				vehicle = vehicleDao.getVehicle(Integer.parseInt(jsonObject.getString("vehicleId")));
				
				vehicleRel = (VehicleRel)vehicle.getVehicleRels().toArray(new VehicleRel[0])[0];
				
				parkingType = parkingTypeDao.getParkingType(jsonObject.getInt("parkingTypeId"));
				vehicleRel.setParkingType(parkingType);					
				vehicleRel.setParking(parking);					
				vehicleRel.setUpdateDate(new Date());
				
				vehicleRelDao.updateVehicleRel(vehicleRel);
			}
			
		}
		else
		{
			parking.setStatusCd(BaseConstants.STATUS_UNUSED);
			parkingDao.updateParking(parking);
			
			if (parking.getVehicleRels().size() > 0)
			{
				vehicleRel = (VehicleRel)parking.getVehicleRels().toArray(new VehicleRel[0])[0];
				
				vehicleRel.setParkingType(null);
				vehicleRel.setParking(null);
				vehicleRel.setUpdateDate(new Date());
				
				vehicleRelDao.updateVehicleRel(vehicleRel);	
				
			}
			
		}
	}

}
